package controller

import (
	"coursedesign/projectGo/common"
	"coursedesign/projectGo/dto"
	"coursedesign/projectGo/model"
	"coursedesign/projectGo/response"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strings"
)

func Login(c *gin.Context) {
	DB := common.GetDB()
	// 获取参数

	var requestManage model.Manager
	c.ShouldBind(&requestManage)
	fmt.Println(requestManage)
	telephone := requestManage.Telephone
	password := requestManage.Password
	// 判断手机号是否存在
	var manager model.Manager
	result := DB.Where("telephone=?", telephone).First(&manager)
	if result.RowsAffected == 0 {
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "用户不存在")
		return
	}
	// 判断密码是否正确
	if strings.Compare(manager.Password, password) != 0 {
		response.Response(c, http.StatusBadRequest, 400, nil, "密码错误")
		return
	}
	// 发放TOKEN
	token, err := common.ReleaseToken(manager)
	if err != nil {
		response.Response(c, http.StatusInternalServerError, 500, nil, "系统异常")
		log.Printf("token generate error: %v", err)
		return
	}

	// 返回结果
	response.Success(c, gin.H{"telephone": telephone, "token": token}, "登录成功")
}

func Info(c *gin.Context) { // 此前已成功验证并将用户信息保存至上下文
	user, _ := c.Get("user") // 获取上下文用户信息
	c.JSON(http.StatusOK, gin.H{"code": 200, "data": gin.H{"user": dto.ToUserDto(user.(model.Manager))}})
}
